package learn.spring.dubbo.framework;

import learn.spring.dubbo.framework.protocol.HttpClient;
import learn.spring.dubbo.framework.protocol.Invocation;
import learn.spring.dubbo.framework.register.RemoteMapRegister;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.List;

/**
 * dubbo接口调用代理
 *
 * @author ShenHao
 */
public class ProxyFactory {

    public static <T> T getProxy(Class interfaceClass) {
        Object instance = Proxy.newProxyInstance(ProxyFactory.class.getClassLoader(), new Class[]{interfaceClass}, new InvocationHandler() {
            @Override
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {

                Invocation invocation = new Invocation(interfaceClass.getName(), method.getName(),
                        args, method.getParameterTypes());

                // 注册中心获取URL
                List<URL> urlList = RemoteMapRegister.get(interfaceClass.getName());

                // 负载均衡, 获取一个生产者URL
                URL url = LoadBalance.random(urlList);

                return HttpClient.post(url.getHostName(), url.getPort(), invocation);
            }
        });

        return (T) instance;
    }
}
